<script setup lang="ts">
import { computed, ref } from 'vue';

import { InfoCircleOutlined, LinkOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

import {
  douying,
  errimage,
  kuaisou,
  pingduoduo,
  taobao,
  xiaohonshu,
} from '#/base';
import { doudianStore, in1688ToDoudianStore } from '#/store/modules';

import { checkBeforePublish } from '../addInSysProduct';

defineOptions({
  name: 'Productlist',
});
const in1688ToDoudian = in1688ToDoudianStore();

const list = computed(() => {
  const datas = in1688ToDoudian.shopTabs.find(
    (item) => item.shopId === in1688ToDoudian.nowSelectTab,
  ).productDetailList;

  return datas;
}); // inject('editDetailItem') as any;
const getPrice = (item: any) => {
  // console.log('item', );
  const maxPrice = Math.max(
    ...item.specPricesV2.map((item: any) => item.price),
  );
  const minPrice = Math.min(
    ...item.specPricesV2.map((item: any) => item.price),
  );
  if (minPrice === maxPrice) {
    return minPrice;
  }
  return `${minPrice}~${maxPrice}`;
};
const categoryId = ref<number>();
const setSelectCategorystatus = ref(false);
function setMaxCategory() {
  if (!categoryId.value) return message.error('请选择分类');
  // console.log('批量设置', list);
  const selectofferId = list.value
    .filter((item: any) => item.isSelect)
    .map((item: any) => {
      return item.offerId;
    });
  if (!selectofferId || selectofferId.length === 0)
    return message.error('请选择商品');
  setSelectCategorystatus.value = false;
  in1688ToDoudian.getItemDetail(selectofferId, categoryId.value);
}

function putDataAll() {
  const selectofferId = in1688ToDoudian.shopTabs
    .find((item) => item.shopId === in1688ToDoudian.nowSelectTab)
    .productDetailList.filter((item: any) => item.isSelect);

  if (!selectofferId || selectofferId.length === 0)
    return message.error('请选择商品');
  // console.log('selectofferId', [{ productDetailList: selectofferId }]);
  checkBeforePublish([
    { shopId: in1688ToDoudian.nowSelectTab, productDetailList: selectofferId },
  ]);
}

function removeSelectProduct() {
  const selectofferId = in1688ToDoudian.shopTabs
    .find((item) => item.shopId === in1688ToDoudian.nowSelectTab)
    .productDetailList.filter((item: any) => item.isSelect)
    .map((item: any) => item.offerId);
  if (!selectofferId || selectofferId.length === 0)
    return message.error('请选择商品');
  in1688ToDoudian.removeSelectProducts(selectofferId);
}
const selectItemRef = ref<any>(in1688ToDoudian.nowSelectGood);
function setEnter(item: any) {
  setTimeout(() => {
    in1688ToDoudian.nowSelectGood = item.offerId;
  }, 0);
}

const doudianStoreModel = doudianStore();
const DoudianCategoryList = computed(
  () => doudianStoreModel.DoudianCategoryList,
);
const categoryIdsOps = ref([]);

const fieldNamesCate = {
  label: 'name',
  value: 'id',
  children: 'children',
};
function setSelectCatergory(data: number[]) {
  categoryId.value = data[data.length - 1];
}
function openurl(id: string) {
  window.open(`https://detail.1688.com/offer/${id}.html`);
}
</script>

<template>
  <div>
    <div>
      <div class="mb-2">
        <a-popover
          v-model:open="setSelectCategorystatus"
          placement="bottomLeft"
          title="批量修改类目"
          trigger="click"
        >
          <template #content>
            <div>
              <div class="mb-2">
                <a-cascader
                  v-model:value="categoryIdsOps"
                  :field-names="fieldNamesCate"
                  :load-data="doudianStoreModel.loadData"
                  :options="DoudianCategoryList"
                  change-on-select
                  placeholder="请选择类目"
                  style="width: 400px"
                  @change="setSelectCatergory"
                >
                  <template #displayRender="{ labels }">
                    <span v-for="(label, index) in labels" :key="index">
                      {{ label }}
                      <span v-if="index + 1 < labels.length"> > </span>
                    </span>
                    <span v-if="labels.length === 0">请选择类目</span>
                  </template>
                </a-cascader>
              </div>
              <div class="flex justify-end">
                <a-button
                  class="mr-2"
                  size="small"
                  @click="setSelectCategorystatus = false"
                >
                  取消
                </a-button>
                <a-button size="small" type="primary" @click="setMaxCategory">
                  确认设置
                </a-button>
              </div>
            </div>
          </template>
          <a-button
            class="mr-2"
            size="small"
            type="primary"
            @click="setSelectCategorystatus = !setSelectCategorystatus"
          >
            批量设置类目
          </a-button>
        </a-popover>

        <a-button
          class="mr-2"
          size="small"
          type="primary"
          @click="removeSelectProduct"
        >
          批量移除商品
        </a-button>
        <a-button class="mr-2" size="small" type="primary" @click="putDataAll">
          立即铺货（{{ list.filter((item: any) => item.isSelect).length }}）
        </a-button>
      </div>
      <!-- {{ in1688ToDoudian.nowSelectGood }} -->
      <div>
        <div
          v-for="(item, index) in list"
          :key="item.offerId"
          :class="{
            'border-gray-300 bg-gray-200': selectItemRef === item.offerId,
          }"
          class="relative mb-2 overflow-hidden rounded-sm border object-none p-2"
        >
          <a-spin :spinning="item.isLodin">
            <div class="flex items-center">
              <a-checkbox v-model:checked="item.isSelect" />
              <div
                class="ml-2 flex flex-1 cursor-pointer items-center"
                @click="
                  // setCibtret = item.offerId
                  selectItemRef = item.offerId;
                  setEnter(item);
                "
              >
                <a-image
                  :fallback="errimage"
                  :src="item.mainPicList[0]"
                  :width="70"
                  class="rounded-sm border"
                />
                <div class="ml-2">
                  <div
                    class="w-56 text-wrap text-sm"
                    @click="() => openurl(item.offerId)"
                  >
                    <a-tooltip
                      :title="`https://detail.1688.com/offer/${item.offerId}.html`"
                    >
                      <LinkOutlined /> {{ item.goodsTitle }}
                    </a-tooltip>
                  </div>
                  <div class="my-0.5 text-xs text-gray-500">
                    上货价: {{ getPrice(item) }}
                  </div>
                  <div class="flex items-center text-xs text-gray-500">
                    <div>密文</div>
                    <div class="ml-2 flex items-center">
                      <template
                        v-for="items in item.supportChannels"
                        :key="items"
                      >
                        <img
                          v-if="items === 'taobao'"
                          :src="taobao"
                          class="mr-1 w-4"
                        />
                        <img
                          v-if="items === 'pinduoduo'"
                          :src="pingduoduo"
                          class="mr-1 w-4"
                        />
                        <img
                          v-if="items === 'xiaohongshu'"
                          :src="xiaohonshu"
                          class="mr-1 w-4"
                        />
                        <img
                          v-if="items === 'douyin'"
                          :src="douying"
                          class="mr-1 w-4"
                        />
                        <img
                          v-if="items === 'kuaishou'"
                          :src="kuaisou"
                          class="mr-1 w-4"
                        />
                      </template>
                      <!-- <img :src="taobao" class="mr-1 w-4" />
                      <img :src="pingduoduo" class="mr-1 w-4" />
                      <img :src="xiaohonshu" class="mr-1 w-4" />
                      <img :src="douying" class="mr-1 w-4" />
                      <img :src="kuaisou" class="mr-1 w-4" /> -->
                    </div>
                  </div>
                  <a-popover
                    v-if="item.errAlls?.errNum > 0"
                    placement="bottomLeft"
                    title="必填未填写"
                  >
                    <template #content>
                      <div
                        v-for="(items, indexs) in item.errAlls.errList"
                        :key="indexs"
                      >
                        <span class="text-red-500">*</span> {{ indexs + 1 }}:
                        {{ items.msg }}
                      </div>
                    </template>
                    <div class="mt-1 text-xs text-red-500">
                      {{ item.errAlls.errNum }}错误 <InfoCircleOutlined />
                    </div>
                  </a-popover>
                </div>
              </div>
              <div class="absolute left-3 top-2 z-10">
                {{ index + 1 }}
              </div>
            </div>
          </a-spin>
        </div>
      </div>
    </div>
  </div>
</template>
